/**
 * 
 */
package com.alstudio.view.text;

import com.loovee.imaohu.R;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

/**
 * @author alonso lee
 * 
 */
public class AnimateTextView extends TextView {
	private CharSequence mText;
	private int mIndex;
	private long mDelay = 100; 

	private AnimateListener mListener;
	private Animation mAnimation;

	public AnimateTextView(Context context) {
		super(context);
		initAnimation(context);
	}

	public AnimateTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initAnimation(context);
	}
	
	private void initAnimation(Context context){
		mAnimation = AnimationUtils.loadAnimation(context, R.anim.fade_in);
		mAnimation.setDuration(80);
	}

	private Handler mHandler = new Handler();
	private Runnable characterAdder = new Runnable() {
		@Override
		public void run() {
			setText(mText.subSequence(0, mIndex++));
//			mAnimation.start();
			if (mIndex <= mText.length()) {
				mHandler.postDelayed(characterAdder, mDelay);
			} else {
				if (mListener != null) {
					mListener.onAnimateEnd();
				}
			}
		}
	};
	
	public void animateText(){
		mText = getText();
		mIndex = 0;

		setText("");
		mHandler.removeCallbacks(characterAdder);
		mHandler.postDelayed(characterAdder, mDelay);
		if (mListener != null) {
			mListener.onAnimateStart();
		}
	}

	public void animateText(CharSequence text) {
		mText = text;
		mIndex = 0;

		setText("");
		mHandler.removeCallbacks(characterAdder);
		mHandler.postDelayed(characterAdder, mDelay);
		if (mListener != null) {
			mListener.onAnimateStart();
		}
	}

	public void setCharacterDelay(long millis) {
		mDelay = millis;
	}

	public void stopAnimate() {
		mHandler.removeCallbacks(characterAdder);
//		if (mListener != null) {
//			mListener.onAnimateEnd();
//		}
	}

	/**
	 * @param mListener
	 *            the mListener to set
	 */
	public void setListener(AnimateListener mListener) {
		this.mListener = mListener;
	}

	public interface AnimateListener {
		public void onAnimateStart();

		public void onAnimateEnd();
	}
}
